//
//  AdvertisingManagement.m
//  DLMovies
//
//  Created by mac1012 on 2017/2/16.
//  Copyright © 2017年 DianlE. All rights reserved.
//

#import "AdvertisingManager.h"
#import <AdSupport/AdSupport.h>

#define  INMOBI_BANNER 1508114604076
#define  INMOBI_INTERSTITIAL 1507679251128
#define  INMOBI_NATIVE 1508669506667

@interface AdvertisingManager ()<IMInterstitialDelegate,IMBannerDelegate,IMNativeDelegate>
{
    
}
@property (nonatomic, strong)CLLocationManager *locationManager;
@property (nonatomic, strong)CLLocation *_location;
@end

@implementation AdvertisingManager

+ (instancetype)shareAdvertisingManager{
    
    static dispatch_once_t onceToken;
    static AdvertisingManager *onceSelf;
    dispatch_once(&onceToken, ^{
        onceSelf = [[self alloc] init];
    });
    return onceSelf;
}

/**
 初始化SDK 并设置信息
 */
- (void)manager{
    srand((unsigned)time(0));
    [IMSdk initWithAccountID:@"c1c3f4e5811345d1bda37f6a3cb24565"];
    _locationManager = [[CLLocationManager alloc] init];
    
    [IMSdk setLocation:_locationManager.location];
    int female = 0;
    female = 1+rand() % 10;
    if (female > 6 ) {
        [IMSdk setGender:kIMSDKGenderMale];
    }else  if(female != 0){
        [IMSdk setGender:kIMSDKGenderFemale];
    }
    int age = 0;
    age = rand() % 10;
    NSLog(@"--%d 年龄:%d",female,age);
    
    if (age > 7) {
        [IMSdk setAgeGroup:kIMSDKAgeGroupBetween18And24];
    }else if (age != 0){
        [IMSdk setAgeGroup:kIMSDKAgeGroupBetween25And29];
    }
    //
    [IMSdk setLogLevel:kIMSDKLogLevelDebug];
}


/**
 懒加载初始化Banner 属性ID 并设置15秒刷新时长
 
 @return 横幅广告
 */
- (IMBanner *)banner{
    if (!_banner ) {
        _banner = [[IMBanner alloc] initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 50) placementId:INMOBI_BANNER delegate:self];
        [_banner setRefreshInterval:7.0f];
        [_banner shouldAutoRefresh:YES];
    }
    return _banner;
}

#pragma mark IMInterstitial
/**
 懒加载初始化interstitial 属性ID
 
 @return 插播广告
 */
- (IMInterstitial *)interstitial{
    
    if (!_interstitial && [self isShowAdvertising]) {
        _interstitial = [[IMInterstitial alloc] initWithPlacementId:INMOBI_INTERSTITIAL delegate:self];
    }
    return _interstitial;
}

/**
 加载插播广告
 */
- (void)loadInterstitial{
    if (![self.interstitial isReady]) {
        [self.interstitial load];
    }
}

#pragma mark IMNative

/**
 懒加载初始化native 属性ID
 
 @return 原生广告-可支持信息流/开屏/前贴
 */
- (IMNative *)native{
    if (!_native && [self isShowAdvertising]) {
        _native = [[IMNative alloc] initWithPlacementId:INMOBI_NATIVE delegate:self];
    }
    return _native;
}


/**
 <#Description#>
 
 */
- (void)nactiveReportAdClick{
    //上报点击事件 --开发者实现跳转
    //[self.native reportAdClick];
    
}

- (void)bindNative:(BOOL)isBind WithCell:(UITableViewCell *)cell{
    if (isBind) {
        //        [IMNative bindNative:self.native toView:cell];
    }else{
        //        [IMNative unBindView:cell];
    }
    
}

/**
 加载开屏广告
 */
- (void)loadNative{
    if (![self.native isReady]) {
        [self.native load];
    }
}

- (void)recyclePrimaryView{
    [self.native recyclePrimaryView];
    
}


/**
 为了安全审核 设置时间戳在特定的时间之后显示广告
 
 @return 是否显示
 */
- (BOOL)isShowAdvertising{
    NSString *dateStr = @"2017-11-03 08:00:00";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *date = [dateFormatter dateFromString:dateStr];
    NSTimeInterval interval = date.timeIntervalSinceNow;
    int hour = (int)(interval/3600);
    if (hour < 0) {
        return YES;
    }
    return NO;
}

- (void)showPop:(UIViewController *)viewController WithType:(AdvertisingType)type WithCloseBlock:(closeBlock)block{
    
    switch (type) {
        case Banner:
        {
            [viewController.view addSubview:self.banner];
            [self.banner load];
        }
            break;
        case Interstitial:
        {
            //常用于游戏过关或者失败
            if ([self.interstitial isReady]) {
                [self.interstitial showFromViewController:viewController];
            }
        }
            break;
            
        default:
            break;
    }
    _closePopBlock = block;
}

- (void)clickAdvertisingPop{
    if (_closePopBlock) {
        _closePopBlock();
        _closePopBlock = nil;
    }
}

- (void)closeAdvertisingPop{
    if (_closePopBlock) {
        _closePopBlock();
        _closePopBlock = nil;
    }
}


#pragma 上报自家服务器统计
- (NSInteger)getTimesTamp
{
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *now=[dateFormatter stringFromDate:[NSDate date]];
    
    NSDate *d1=[dateFormatter dateFromString:now];
    
    return  [d1 timeIntervalSince1970]*1;
    
}

- (void)rePortServer:(long long)placementId isShowSucces:(BOOL)isSucces{
    
    NSString *showString = isSucces ? @"show": @"click";
    NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString *timestamp = [NSString stringWithFormat:@"%ld",[self getTimesTamp]];
    //[NSNumber numberWithUnsignedLongLong:<#(unsigned long long)#>]
    NSString *placementIdStr = [NSString stringWithFormat:@"%lld",placementId];
    
    NSString *parmStr = [NSString stringWithFormat:@"t=%@&i=%@&d=%@&a=%@",showString,idfa,timestamp,placementIdStr];
    NSString *urlStr = [NSString stringWithFormat:@"http://vclient.moopay.cn/count/index?%@",parmStr];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request setHTTPMethod:@"GET"];
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request];
    [task resume];
}

#pragma mark IMBanner
- (void)banner:(IMBanner *)banner didFailToLoadWithError:(IMRequestStatus *)error {
    NSLog(@"Banner Load failed With Error: %@",error.description);
}
- (void)banner:(IMBanner *)banner didInteractWithParams:(NSDictionary *)params {
    NSLog(@"Banner Did Interact With Params: %@",params);
}
- (void)banner:(IMBanner *)banner rewardActionCompletedWithRewards:(NSDictionary *)rewards {
    NSLog(@"Reward Action Comleted with Rewards %@",rewards);
}
- (void)bannerDidDismissScreen:(IMBanner *)banner {
    NSLog(@"Banner Did Dismiss Screen");
}
- (void)bannerDidFinishLoading:(IMBanner *)banner {
    
    [self rePortServer:banner.placementId isShowSucces:YES];
    NSLog(@"Banner Finished Loading");
}
- (void)bannerDidPresentScreen:(IMBanner *)banner {
    NSLog(@"Banner Did Present Screen");
}
- (void)bannerWillDismissScreen:(IMBanner *)banner {
    NSLog(@"Banner Will Dismiss Screen");
}
- (void)bannerWillPresentScreen:(IMBanner *)banner {
    NSLog(@"Banner Will Present Screen");
}
- (void)userWillLeaveApplicationFromBanner:(IMBanner *)banner {
    [self rePortServer:banner.placementId isShowSucces:NO];
    NSLog(@"User Will Leave Application from Banner");
}

#pragma mark IMInterstitialDelegate
- (void)interstitial:(IMInterstitial *)interstitial didFailToLoadWithError:(IMRequestStatus *)error{
    NSLog(@"Interstitial Failed to load interstitial with error: %@",error.description);
}
- (void)interstitial:(IMInterstitial *)interstitial didFailToPresentWithError:(IMRequestStatus *)error {
    NSLog(@"Interstitial Failed to Present Interstitial with error : %@",error.description);
}
- (void)interstitial:(IMInterstitial *)interstitial didInteractWithParams:(NSDictionary *)params {
    NSLog(@"Interstitial did interact with param : %@",params);
}
- (void)interstitial:(IMInterstitial *)interstitial rewardActionCompletedWithRewards:(NSDictionary *)rewards {
    NSLog(@"Interstitial reward action completed with Rewards : %@",rewards);
}
- (void)interstitialDidDismiss:(IMInterstitial *)interstitial {
    NSLog(@"Interstitial Did Dismiss");
}
- (void)interstitialDidFinishLoading:(IMInterstitial *)interstitial {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"interstitialDidFinishLoading" object:nil];
    
    NSLog(@"Interstitial Did Finish Loading");
    
}
- (void)interstitialDidPresent:(IMInterstitial *)interstitial {
    NSLog(@"Interstitial Did Present");
}
- (void)interstitialWillDismiss:(IMInterstitial *)interstitial {
    NSLog(@"Interstitial Will Dismiss");
}
- (void)interstitialWillPresent:(IMInterstitial *)interstitial {
    NSLog(@"Interstitial Will Presen");
}

#pragma mark IMNativeDelegate
/*The native ad notifies its delegate that it is ready. Fetching publisher-specific ad asset content from native.adContent. The publisher will specify the format. If the publisher does not provide a format, no ad will be loaded.*/
-(void)nativeDidFinishLoading:(IMNative*)native{
    [self nactiveReportAdClick];
    [self rePortServer:1508669506667 isShowSucces:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"nativeDidFinishLoading" object:nil];
    
}
/*The native ad notifies its delegate that an error has been encountered while trying to load the ad.Check IMRequestStatus.h for all possible errors.Try loading the ad again, later.*/
-(void)native:(IMNative*)native didFailToLoadWithError:(IMRequestStatus*)error{
    NSLog(@"Native Ad load Failed");
    //[NSNotificationCenter.defaultCenter postNotificationName:@"nativeDidFinishDiss" object:nil];
}
/* Indicates that the native ad is going to present a screen. */ -(void)nativeWillPresentScreen:(IMNative*)native{
    NSLog(@"Native Ad will present screen");
    
}
/* Indicates that the native ad has presented a screen. */
-(void)nativeDidPresentScreen:(IMNative*)native{
    NSLog(@"Native Ad did present screen");
}
/* Indicates that the native ad is going to dismiss the presented screen. */
-(void)nativeWillDismissScreen:(IMNative*)native{
    NSLog(@"Native Ad will dismiss screen");
}
/* Indicates that the native ad has dismissed the presented screen. */
-(void)nativeDidDismissScreen:(IMNative*)native{
    NSLog(@"Native Ad did dismiss screen");
}
/* Indicates that the user will leave the app. */
-(void)userWillLeaveApplicationFromNative:(IMNative*)native{
    
    [self rePortServer:1508669506667 isShowSucces:NO];
    NSLog(@"User leave");
}

@end
